<template>
    <SysDialog :title="dialog.title" :visible="dialog.visible" :width="dialog.width" :height="dialog.height"
    @onClose="onClose" @onConfirm="commit">
        <template v-slot:content>
            <el-form :model="addModel" ref="addFormRef" :rules="rules" label-width="80px" :inline="false" size="default">
                <el-form-item prop="title" label="标题">
                    <el-input v-model="addModel.title"></el-input>
                </el-form-item>
                <el-form-item prop="goodsName" label="菜品">
                    <el-select v-model="addModel.goodsName" placeholder="请选择分类" size="default" style="width: 240px">
                        <el-option v-for="item in selectData" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="orderId" label="序号">
                    <el-input v-model="addModel.orderId"></el-input>
                </el-form-item>
                <el-form-item prop="status" label="上下架">
                    <el-radio-group v-model="addModel.status">
                        <el-radio :value="'0'">下架</el-radio>
                        <el-radio :value="'1'">上架</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="images" label="广告图片">
                    <UploadImage @get-img="getImg" :oldUrl="oldUrl" :fileList="fileList"></UploadImage>
                </el-form-item>
            </el-form>
        </template>
    </SysDialog>
</template>

<script setup lang="ts">
import UploadImage from '@/components/UploadImage.vue'
import { AdvertisementType } from '@/api/advertisement/AdvertisementModel';
import SysDialog from '@/components/SysDialog.vue';
import useDialog from '@/tools/useDialog';
import { ElMessage, FormInstance,UploadUserFile } from 'element-plus';
import { nextTick, reactive,ref } from 'vue';
import { EditType, NewType } from '@/type/BaseType';
import useSelectCategory from '@/module/advertisement/useSelectCategory';
import { addAdvApi,editAdvApi } from '@/api/advertisement';
//下拉菜品
const { getSelect,selectData} = useSelectCategory()
//图片初始值
const fileList = ref<Array<UploadUserFile>>([])
//回显的图片
const oldUrl = ref<Array<{ url: string }>>([])
//图片地址
const imgUrl = ref<Array<{ url: string }>>([])
//表单ref属性
const addFormRef = ref<FormInstance>()
//弹框属性
const { dialog,onConfirm,onClose,onShow} = useDialog()
//弹框显示
const show = (type: string, row?:AdvertisementType)=>{
    //清空新增里面的图片
    imgUrl.value = []
    oldUrl.value = []
    fileList.value = []
    dialog.height = 380
    //查询下拉菜品
    getSelect()
    onShow()
    //编辑时显示出数据
    if (row && type == EditType.EDIT) {
        dialog.title = '编辑'
        nextTick(() => {
            Object.assign(addModel, row)
            //图片回显
            if (addModel.images) {
                //逗号分隔的字符串转为数组
                let imgs = addModel.images.split(",")
                for (let i = 0; i < imgs.length; i++) {
                    let img = {
                        name: '',
                        url: ''
                    }
                    img.name = imgs[i]
                    img.url = imgs[i]
                    fileList.value.push(img)
                    oldUrl.value.push({ url: imgs[i] })
                }
            }
        })
    }
    //设置编辑的属性：0：新增、1：编辑
    addModel.type = type;
    //清空表单
    addFormRef.value?.resetFields()
}
//将方法显露出去给父组件调用
defineExpose({
    show
})
//表单绑定的对象
const addModel = reactive<AdvertisementType>({
    type:'',
    advId:'',
    goodsName:'',
    title:'',
    images:'',
    status:'1',
    orderId:'',
})
//表单验证规则
const rules = reactive({
    goodsName:[{
        required: true,
        message: '请选择菜品',
        trigger: "blur",
    },],
    title:[{
        required: true,
        message: '请填写标题',
        trigger: "blur",
    },],
    images:[{
        required: true,
        message: '请上传图片',
        trigger: "blur",
    },],
    orderId:[{
        required: true,
        message: '请填写序号',
        trigger: "blur",
    },],
    status:[{
        required: true,
        message: '请选择是否上架',
        trigger: "blur",
    },],
})
//图片上传地址
const getImg = (img: NewType) => {
    imgUrl.value = oldUrl.value.concat(img.newImgUrl)
    if (img.deleteUrl.length > 0) {
        let newArr = imgUrl.value.filter((x) => !img.deleteUrl.some((item) => x.url === item.url))
        imgUrl.value = newArr
    }
    //把图片路径拼接为逗号分隔的字符串
    let url = ""
    for (let i = 0; i < imgUrl.value.length; i++) {
        url = url + imgUrl.value[i].url + ","
    }
    addModel.images = url.substring(0, url.lastIndexOf(","))
}
//注册事件
const emists = defineEmits(['onFresh'])
//表单提交
const commit = ()=>{
    addFormRef.value?.validate(async (valid) => {
        if (valid) {
            let result = null
            if (addModel.type == EditType.ADD) {
                result = await addAdvApi(addModel)
            } else {
                result = await editAdvApi(addModel)
            }
            if (result && result.code == 200) {
                ElMessage.success(result.msg)
                emists('onFresh')
                onClose()
            }
        }
    })
}
</script>

<style scoped>

</style>